package cn.kone.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.kone.constants.Constants;
import cn.kone.mapper.OrderMapper;
import cn.kone.pojo.domain.Login;
import cn.kone.pojo.domain.Order;
import cn.kone.pojo.domain.OrderBill;
import cn.kone.pojo.domain.OrderProfitsharing;
import cn.kone.pojo.dto.LocationRedisDTO;
import cn.kone.pojo.dto.NewOrderDTO;
import cn.kone.pojo.dto.OrderPayDTO;
import cn.kone.pojo.vo.OrderDetail;
import cn.kone.remote.api.BigdataFeignApi;
import cn.kone.remote.api.RuleFeignApi;
import cn.kone.remote.dto.param.OrderDto;
import cn.kone.remote.dto.param.ProfitsharingDto;
import cn.kone.remote.dto.result.OrderProfitsharingResult;
import cn.kone.remote.dto.result.OrderResult;
import cn.kone.remote.result.DriverPointResult;
import cn.kone.result.JSONResult;
import cn.kone.service.IOrderBillService;
import cn.kone.service.IOrderProfitsharingService;
import cn.kone.service.IOrderService;
import cn.kone.utils.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.PullResult;
import org.apache.rocketmq.client.consumer.PullStatus;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author yuyu
 * @since 2024-03-25
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {


    @Autowired
    private IOrderBillService orderBillService;

    @Autowired
    private RuleFeignApi ruleFeignApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private BigdataFeignApi bigdataFeignApi;

    @Autowired
    private IOrderProfitsharingService orderProfitsharingService;

    @Override
    public Object addOrder(Order order) {
        //保存order表订单表
        long orderId = IdUtil.createSnowflake(0, 0).nextId();
        order.setId(orderId);
        order.setOrderNo("" + orderId);
        order.setCustomerId(StpUtil.getLoginIdAsLong());
        order.setRealMileage(new BigDecimal("0"));
        order.setReturnMileage(new BigDecimal("0"));
        order.setCreateTime(new Date());


        OrderDto orderDto = new OrderDto();
        orderDto.setExpectsMileage(order.getExpectsMileage());
        orderDto.setCreateTime(order.getCreateTime());
        OrderResult orderResult = ruleFeignApi.addOrder(orderDto).getData();
        order.setExpectsOrderAmount(orderResult.getExpectsAmount()); //预计价格


        order.setRealOrderAmount(new BigDecimal("0"));
        order.setStatus(0);
        order.setRemark("");
        //将缓存的乘客信息取出来存进order对象中
        Login login = (Login) redisTemplate.boundValueOps("one" + StpUtil.getLoginIdAsLong()).get();
        order.setCustomerName(login.getNickName());
        order.setCustomerPhone(login.getPhone());
        order.setCustomerPhoto(login.getAvatar());
        save(order);

        //保存订单账单表
        OrderBill orderBill = new OrderBill();

        // 使用BeanUtils.copyProperties()方法将orderResult对象的属性复制到orderBill对象中
        // 该方法会将orderResult对象中的每个属性值复制到orderBill对象中对应的属性上
        // 如果属性名在两个对象中匹配，则将属性值复制过去，否则忽略不处理
        BeanUtils.copyProperties(orderResult, orderBill);

        orderBill.setId(orderId);
        orderBill.setOrderId(orderId);
        orderBill.setRealOrderAmount(orderResult.getExpectsAmount());
        orderBill.setRealPayAmount(orderResult.getExpectsAmount());

        orderBill.setOrderNo("" + orderId);
        orderBill.setCreateTime(new Date());
        orderBillService.save(orderBill);

        //创建接受信息的点
        Point p1 = new Point(new Point(Double.valueOf("114.311582"), Double.valueOf("30.598467")));
        redisTemplate.boundGeoOps("GEO").add(p1, 1);
        Point p2 = new Point(new Point(Double.valueOf("114.311582"), Double.valueOf("30.598467")));
        redisTemplate.boundGeoOps("GEO").add(p2, 2);


        // 创建一个圆形区域 c，中心点坐标为经度 120.311582、纬度 60.598467，半径为 10 公里
        Circle circle = new Circle(new Point(Double.valueOf("114.311582"), Double.valueOf("30.598467")), new Distance(10, Metrics.KILOMETERS));

        //创建配置的参数
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        // 设置查询参数，包括返回结果包含坐标、距离信息，按距离升序排序，限制返回结果数量为5个
        args.includeCoordinates().includeDistance().sortAscending().limit(5);

        // 从 Redis 中查询指定圆形区域范围内的地理位置，返回 GeoResults 对象
        GeoResults geoResults = redisTemplate.boundGeoOps("GEO").radius(circle, args);
        System.out.println("```````````````````````````````````````````````");
        System.out.println(geoResults);
        System.out.println("```````````````````````````````````````````````");
        //创建一个对象用来封装前端所需要的信息
        NewOrderDTO newOrderDTO = new NewOrderDTO();
        newOrderDTO.setOrderNo(order.getOrderNo()); //将订单号存进NewOrderDTO中以方便司机抢单

        System.out.println(geoResults.getContent());
        List<GeoResult> list = geoResults.getContent();
        System.out.println(list);
        //遍历集合将结果集封装到NewOrderDTO
        for (GeoResult<RedisGeoCommands.GeoLocation> geoResult : list) {
            newOrderDTO.setDistance(
                            BigDecimal.valueOf(geoResult.getDistance().getValue()))
                    .setMileage(order.getExpectsMileage())
                    .setExpectsFee(orderResult.getExpectsAmount())
                    .setFrom(order.getStartPlace())
                    .setTo(order.getEndPlace());

            //准备消息
            Message<NewOrderDTO> message = MessageBuilder.withPayload(newOrderDTO).build();
            //发送消息
            rocketMQTemplate.syncSend("order_topic:order_tags" + geoResult.getContent().getName().toString(), message);

        }
        //将订单信息存储在redis缓存中  key为:order:+订单号
        redisTemplate.boundValueOps("order:" + order.getOrderNo()).set(order);

        return order.getOrderNo();
    }

    //乘客取消订单,修改订单状态
    @Override
    public Object updateOrder(String orderNo) {
        //查询出订单对象
        Order order = getById(orderNo);
        AssertUtil.isNotNull(order, "订单不存在~~");
        order.setStatus(Constants.Customer.CUSTOMER_CANCELED);//乘客撤单 修改订单状态
        updateById(order);
        return null;
    }


    //查询乘客下单的订单状态并且返回
    @Override
    public Object getOrder() {
        //根据乘客ID查询出订单对象
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getCustomerId, StpUtil.getLoginIdAsLong()).le(Order::getStatus, 6));
//        AssertUtil.isNotNull(order, "订单不存在~~~");


        return order;
    }


    @Autowired
    private DefaultMQPullConsumer pullConsumer;

    //获取消息
    @Override
    public Object pullOrder() {

        // 创建一个空的 ArrayList 对象，用于存储拉取到的订单消息
        ArrayList<NewOrderDTO> newOrder = new ArrayList<NewOrderDTO>();

        try {
            // 获取订阅消息主题为 "order_topic" 的消息队列集合
            Set<MessageQueue> messageQueues = pullConsumer.fetchSubscribeMessageQueues("order_topic");

            // 遍历消息队列集合，对每个消息队列执行以下操作
            for (MessageQueue messageQueue : messageQueues) {

                // 获取当前消息队列的消费进度
                long offset = pullConsumer.fetchConsumeOffset(messageQueue, true);

                // 从消息队列拉取消息，参数包括消息队列、消息标签、消费进度偏移量和拉取消息的数量
                PullResult pullResult = pullConsumer.pull(messageQueue, "order_tags1", offset, 5);

                // 判断拉取消息的结果是否有效，若有效则继续执行
                if (pullResult != null && pullResult.getPullStatus().equals(PullStatus.FOUND)) {

                    // 获取拉取到的消息列表
                    List<MessageExt> messageList = pullResult.getMsgFoundList();

                    // 遍历消息列表，将消息内容解析为 NewOrderDTO 对象，并添加到 newOrder 集合中
                    for (MessageExt messageExt : messageList) {
                        String json = new String(messageExt.getBody(), "UTF-8");
                        NewOrderDTO newOrderDTO = JSON.parseObject(json, NewOrderDTO.class);
                        newOrder.add(newOrderDTO);
                    }

                    // 更新消息队列的消费进度为下一次拉取消息的起始偏移量
                    pullConsumer.updateConsumeOffset(messageQueue, pullResult.getNextBeginOffset());
                }
            }
            // 返回存储了拉取到的订单消息的 newOrder 列表
            return newOrder;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    //司机抢单
    @Override
    public Object killOrder(String orderNo) {

        //校验订单号是否存在
        AssertUtil.isNotEmpty(orderNo, "订单号不存在~~~");
        //在redis中取出订单
        Order order = (Order) redisTemplate.boundValueOps("order:" + orderNo).get();
        //校验订单是否存在
        AssertUtil.isNotNull(order, "订单不存在~~~");
        //校验订单状态是否为0(就是等待接单)
        AssertUtil.isEquals(order.getStatus(), Constants.Customer.WAITING_FOR_ORDER, "订单状态异常~~~");

        //修改订单订单状态为已接单状态 (状态为:1)
        order.setStatus(Constants.Customer.ORDER_ACCEPTED);
        Date date = new Date(); // 创建一个新的 Date 对象，表示当前时间
        order.setUpdateTime(date); // 将当前时间设置为订单的更新时间
        order.setAcceptTime(date); // 将当前时间设置为订单的接单时间
        order.setDriverId(StpUtil.getLoginIdAsLong()); //司机ID

        //在登陆的时候就将登陆的司机的id存进Redis中,现在取出来封装在order对象中,返回给前端
        Login login = (Login) redisTemplate.boundValueOps("one" + StpUtil.getLoginIdAsLong()).get();
        order.setDriverName(login.getNickName());
        order.setDriverPhoto(login.getAvatar());
        order.setDriverPhone(login.getPhone());

        updateById(order); //调用修改的方法

        redisTemplate.delete("order:" + orderNo); //将redis中的这个订单删除掉,表示司机已经抢到这个订单了

        return order;
    }


    //司机到达代驾地点,更改订单状态为2(司机已到达)
    @Override
    public Object updateOrderStatus(String orderNo) {
        //校验订单编号是否为空
        AssertUtil.isNotEmpty(orderNo, "订单不存在~~");
        //根据订单编号查询出订单信息
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        //校验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");

        order.setStatus(Constants.Customer.DRIVER_ARRIVED); //将订单状态改为司机已到达
        Date date = new Date();
        order.setArriveTime(date);
        order.setUpdateTime(date);
        updateById(order);
        return null;
    }


    //查询订单状态返回给前端根据状态进行跳转
    @Override
    public Object loadOrder() {

        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getDriverId, StpUtil.getLoginIdAsLong())
                .ge(Order::getStatus, 1).le(Order::getStatus, 6));
        AssertUtil.isNotNull(order, "订单不存在~~~");


        return order;
    }


    //司乘同显,通过订单号查询订单对象,并且返回给前端,对象里有位置的经纬度
    @Override
    public Object loadOrderLocation(String orderNo) {
        //校验订单编号是否为空
        AssertUtil.isNotEmpty(orderNo, "订单不存在~~");
        //根据订单编号查询出订单信息
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        //校验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");
        return order;
    }

    //司机开始代驾,修改订单状态为3开始代驾
    @Override
    public Object startDrivingHandle(String orderNo) {
        //校验订单编号是否为空
        AssertUtil.isNotEmpty(orderNo, "订单不存在~~");
        //根据订单编号查询出订单信息
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        //校验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");

        order.setStatus(Constants.Customer.JOURNEY_STARTED); //将订单状态改为开始代驾
        Date date = new Date();  //创建一个时间 时间设定为当前时间
        order.setStartTime(date); //订单开始时间
        order.setUpdateTime(date);//订单修改时间
        updateById(order); //执行修改的方法

        //根据订单账号查询账单
        OrderBill orderBill = orderBillService.getById(order.getOrderNo());
        //校验账单是否为空
        AssertUtil.isNotNull(orderBill, "没有此账单~~~");

        //使用糊涂工具包,用司机到达时间减去代驾开始时间得到,等待时长
        Long WaitingMinute = DateUtil.between(order.getArriveTime(), order.getStartTime(), DateUnit.MINUTE);
        orderBill.setWaitingMinute(WaitingMinute.intValue()); //持久化到账单表中
        orderBillService.updateById(orderBill); //调用修改的方法修改账单信息
        return null;
    }


    //将封装的坐标信息和订单信息,存进Redis
    @Override
    public Object LocationRedis(LocationRedisDTO locationRedisDTO) {

        //将订单的编号和位置信息缓存到Redis中
        redisTemplate.boundValueOps("LocationRedis" + StpUtil.getLoginIdAsLong()).set(locationRedisDTO);

        return null;
    }


    //从Redis中取出数据返回给前端
    @Override
    public Object getLocationRedis(String orderNo) {
        //校验订单编号是否为空
        AssertUtil.isNotEmpty(orderNo, "订单编号不存在~~");
        //根据订单号查询到订单
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        //检验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");
        //从Redis中取出数据
        LocationRedisDTO locationRedisDTO = (LocationRedisDTO) redisTemplate.boundValueOps("LocationRedis" + order.getDriverId()).get();
        //校验Redis数据是否为空
        AssertUtil.isNotNull(locationRedisDTO, "Redis中没有数据~~~");

        return locationRedisDTO;
    }



    //给前端用户页面的司乘同显的订单详情页面进行回显
    @Override
    public Object getOrderDetail(String orderNo) {

        Order order = getById(orderNo);
        AssertUtil.isNotNull(order, "没有这个订单~~~");

        OrderBill orderBill = orderBillService.getById(order.getOrderNo());
        //校验账单是否为空
        AssertUtil.isNotNull(orderBill, "没有此账单~~~");


        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrder(order);
        orderDetail.setOrderBill(orderBill);

        OrderProfitsharing orderProfitsharing = orderProfitsharingService.getById(orderNo);//分账表对象
        AssertUtil.isNotNull(orderProfitsharing, "没有这个分账单~~~");
        orderDetail.setOrderProfitsharing(orderProfitsharing);
        return orderDetail;
    }

    //app司机端点击结束代驾,后台修改订单状态
    @Override
    public Object endDrivingHandle(String orderNo) {
        //校验订单编号是否为空
        AssertUtil.isNotEmpty(orderNo, "订单不存在~~~");
        //根据订单编号查询出订单信息
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        //校验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");

        order.setStatus(Constants.Customer.JOURNEY_ENDED); //将订单状态改为结束代驾
        Date date = new Date();  //创建一个时间 时间设定为当前时间
        order.setEndTime(date); //订单开始时间
        order.setUpdateTime(date);//订单修改时间
        updateById(order); //执行修改的方法

        JSONResult<List<DriverPointResult>> jsonResult = bigdataFeignApi.getPoints(orderNo);
        System.out.println("```````````````````````````");
        System.out.println("这是bigdataFeign接口调用传递的参数,jsonResult:"+jsonResult);
        System.out.println("```````````````````````````");
//        AssertUtil.isTrue(jsonResult.isSuccess(), "远程调用bigdata服务失败哦~~~");
        List<DriverPointResult> driverPointResults = jsonResult.getData(); //拿到data里面的数据
        System.out.println("这是拿到的data数据:" + driverPointResults);
        //创建一个计算真实里程的方法 将driverPointResults的坐标信息传递过去用于计算
        BigDecimal realMileage = calculatedMileage(driverPointResults);

        //根据真实的里程计算出真实的价格
        OrderDto orderDto = new OrderDto();
        orderDto.setExpectsMileage(realMileage);
        orderDto.setCreateTime(order.getCreateTime());
        OrderResult orderResult = ruleFeignApi.addOrder(orderDto).getData();

        OrderBill orderBill = orderBillService.getById(orderNo);//根据订单号查询到账单信息
        AssertUtil.isNotNull(orderBill,"没有此账单~~~");//校验账单信息是否为空
        order.setRealMileage(realMileage); //真实里程
        order.setReturnMileage(realMileage); //返程里程
        order.setRealOrderAmount(orderResult.getExpectsAmount().add(orderBill.getWaitingAmount()).add(orderBill.getFavourAmount()));//计算真实价格
        updateById(order);//保存数据

        orderBill.setRealOrderAmount(order.getRealOrderAmount());
        orderBillService.updateById(orderBill);

        return null;
    }



    //计算里程方法
    private BigDecimal calculatedMileage(List<DriverPointResult> driverPointResults) {

        // 初始化总里程为 0
        BigDecimal totalMileage = BigDecimal.ZERO;

        // 循环遍历司机位置信息列表，但是到倒数第二个位置停止，因为最后一个位置没有下一个位置与之对应
        for (int i = 0; i < driverPointResults.size() - 1; i++) {
            // 获取当前位置信息和下一个位置信息
            DriverPointResult pre = driverPointResults.get(i);// 当前位置信息
            DriverPointResult next = driverPointResults.get(i + 1);// 下一个位置信息

            BigDecimal distance = mapCalculatedMileage(pre, next);// 调用方法计算当前位置到下一个位置之间的距离
            totalMileage = totalMileage.add(distance);// 将距离累加到总里程中
        }


        return totalMileage; //返回累加总里程
    }

    @Autowired
    private RestTemplate restTemplate;

    private BigDecimal mapCalculatedMileage(DriverPointResult pre, DriverPointResult next) {
        // 构造请求 URL，使用腾讯地图 API 计算两点之间的驾车距离
        String url = "https://apis.map.qq.com/ws/distance/v1/matrix/?mode=driving&from=39.984092,116.306934&to=39.981987,116.362896&key=S4RBZ-YDCWZ-5RLXZ-TCROO-XSRWS-G6BGM";
        // 使用 RestTemplate 发起 HTTP GET 请求，获取响应数据
        String restTemplateForObject = restTemplate.getForObject(url, String.class);

        int distance = JSON.parseObject(restTemplateForObject).getJSONObject("result").getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getIntValue("distance");
        System.out.println(distance);

        int duration = JSON.parseObject(restTemplateForObject).getJSONObject("result").getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getIntValue("duration");
        System.out.println(duration);

        return new BigDecimal("" + distance).divide(new BigDecimal("" + 1000)); //准换单位将米转换为千米
    }


    //司机确认费用
    @Override
    @Transactional //加上本地事务
    public Object confirmFree(OrderBill orderBill) {
        //查询账单对象
        OrderBill oneOrderBill = orderBillService.getById(orderBill.getOrderNo());
        oneOrderBill.setTollAmount(orderBill.getTollAmount());
        oneOrderBill.setOtherAmount(orderBill.getOtherAmount());
        oneOrderBill.setParkingAmount(orderBill.getParkingAmount());
        //真实金额
        oneOrderBill.setRealOrderAmount(oneOrderBill.getRealOrderAmount().add(oneOrderBill.getTollAmount()).add(oneOrderBill.getParkingAmount()).add(oneOrderBill.getOtherAmount()));
        orderBillService.updateById(oneOrderBill);

        //根据订单编号查询出订单信息
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderBill.getOrderNo()));
        //校验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");
        order.setRealOrderAmount(oneOrderBill.getRealOrderAmount());
        order.setStatus(Constants.Customer.DRIVER_CONFIRMED_FARE);//订单状态修改为5确认费用
        updateById(order);


        //确认费用未完待续↓
        ProfitsharingDto profitsharingDto = new ProfitsharingDto();
        profitsharingDto.setOrderAmount(order.getRealOrderAmount());
        profitsharingDto.setOrderCancelCount(2);
        profitsharingDto.setOrderComplaintCount(2);

        JSONResult<OrderProfitsharingResult> jsonResult = ruleFeignApi.calprofitsharing(profitsharingDto);//核心代码
        AssertUtil.isTrue(jsonResult.isSuccess(), "远程调用rule失败");
        OrderProfitsharingResult result = jsonResult.getData();
        System.out.println(result);


        OrderProfitsharing orderProfitsharing = new OrderProfitsharing();
        orderProfitsharing.setId(order.getId());
        orderProfitsharing.setOrderId(order.getId());
        orderProfitsharing.setOrderNo(order.getOrderNo());
        orderProfitsharing.setOrderAmount(order.getRealOrderAmount());
        orderProfitsharing.setStatus(0);//0未分账

        orderProfitsharing.setPlatformIncomeAmount(result.getPlatformIncomeAmount());
        orderProfitsharing.setDriverIncomeAmount(result.getDriverIncomeAmount());
        orderProfitsharing.setPlatformRate(result.getPlatformRate());
        orderProfitsharing.setDriverRate(result.getDriverRate());

        // 获取登录用户信息
        Login login = (Login) redisTemplate.boundValueOps("one:"+StpUtil.getLoginIdAsLong()).get();

        orderProfitsharing.setToUserOpenId(login.getOpenId());// 设置分账记录的收款方openid为登录用户的openid
        orderProfitsharing.setCreateTime(new Date());// 设置创建时间为当前时间

        // 调用订单分账服务的保存方法，将订单分账记录保存到数据库中
        orderProfitsharingService.saveOrUpdate(orderProfitsharing);

        return null;
    }


    //发送账单,修改状态
    @Override
    public Object sendorderBill(String orderNo) {
        //先查询是否有次订单
        Order order = getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
        //校验订单是否为空
        AssertUtil.isNotNull(order, "订单不存在~~~");


        //将订单状态改为未付款
//        order.setStatus(Constants.Customer.UNPAID);
//        order.setUpdateTime(new Date()); //新增修改时间
//        updateById(order); //修改订单持久化到mysql

        OrderPayDTO orderPayDTO = new OrderPayDTO();
        orderPayDTO.setOrderAmount(order.getRealOrderAmount());
        orderPayDTO.setOrderNo(order.getOrderNo());
        orderPayDTO.setCustomerId(order.getCustomerId());
        orderPayDTO.setSubject("订单费用为:"+order.getRealOrderAmount());


        //创建消息
        Message<OrderPayDTO> message = MessageBuilder.withPayload(orderPayDTO).build();
        //发送消息
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction("orderPay_topic:orderPay_tags", message, order);
        AssertUtil.isTrue(transactionSendResult.getSendStatus()== SendStatus.SEND_OK,"账单发送失败~~~");

        return null;
    }


//    private static BigDecimal mapCalculatedMileage2() {
//        // 构造请求 URL，使用腾讯地图 API 计算两点之间的驾车距离
//        String url = "https://apis.map.qq.com/ws/distance/v1/matrix/?mode=driving&from=39.984092,116.306934&to=39.981987,116.362896&key=S4RBZ-YDCWZ-5RLXZ-TCROO-XSRWS-G6BGM";
//        // 使用 RestTemplate 发起 HTTP GET 请求，获取响应数据
//        String restTemplateForObject = new RestTemplate().getForObject(url, String.class);
//        System.out.println("这是:" + restTemplateForObject);
//
////        int distance = JSON.parseObject(restTemplateForObject).getJSONObject("result").getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getIntValue("distance");
////        System.out.println(distance);
////
////        int duration = JSON.parseObject(restTemplateForObject).getJSONObject("result").getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0).getIntValue("duration");
////        System.out.println(duration);
//
//        return null;
//    }
//
//    public static void main(String[] args) {
//        mapCalculatedMileage2();
//    }
}
